﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Auth.Application.Dtos;
using Auth.Application;
using Auth.Web.Models;
using SqlSugar;
using Auth.SqlSugar;
using Microsoft.AspNetCore.Http;
using System.Linq;
using Auth.Utility;

namespace Auth.Web.Controllers
{
    public class RoleController : AuthControllerBase
    {
        private readonly IRoleAppService _service;
        private readonly IHttpContextAccessor _httpContext;
        private readonly IMenuAppService _menuAppService;
        public RoleController(IRoleAppService service, IHttpContextAccessor httpContext, IMenuAppService menuAppService)
        {
            _service = service;
            _httpContext = httpContext;
            _menuAppService = menuAppService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult EditPage(string id)
        {
            if (!string.IsNullOrEmpty(id))
                ViewData["id"] = id;
            return View();
        }
        public IActionResult AuthRole(string ids)
        {
            if (!string.IsNullOrEmpty(ids))
                ViewData["ids"] = ids;
            else
                throw new MessageBox("请至少选择一个角色");
            return View();
        }
        public JsonResult GetRoleTableCols()
        {
            List<LayuiColsModel> colsList = new List<LayuiColsModel>();
            colsList = GetTableCols<RoleDto>();
            return Json(new ReturnModel() { Data = colsList });
        }
        /// <summary>
        /// 获取角色下拉选择JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRoleSelectData()
        {
            var roles = _service.GetAll();
            List<SelectModel> roleList = new List<SelectModel>();
            foreach (var item in roles)
            {
                SelectModel model = new SelectModel
                {
                    Value = item.Id,
                    Name = item.Name
                };
                roleList.Add(model);
            }
            return Json(new ReturnModel() { Data = roleList });
        }
        /// <summary>
        /// 新增或编辑功能
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public IActionResult Edit(RoleDto dto)
        {
            if (!ModelState.IsValid)
            {
                return Json(new ReturnModel
                {
                    Success = false,
                    Msg = GetModelStateError()
                });
            }
            if (string.IsNullOrEmpty(dto.Id))
            {
                dto.CreateTime = DateTime.Now;
                dto.CreateUserId = _httpContext.HttpContext.Session.GetString("CurrentUserId");
            }

            if (_service.InsertOrUpdate(dto))
            {
                return Json(new ReturnModel() { Success = true, Msg = "操作成功" });
            }

            return Json(new ReturnModel
            {
                Success = false,
                Msg = "操作失败"
            });
        }

        [HttpPost]
        public IActionResult GetAllPageList(int page, int limit, string searchParam)
        {
            List<IConditionalModel> conModels = ConditionHelper.GetCondition(searchParam);
            var result = _service.GetTableList(page, limit, conModels);
            return Json(result);
        }

        public IActionResult DeleteMuti(string ids)
        {
            try
            {
                string[] idArray = ids.Split(',');
                //去除空字符串
                var delIds = idArray.Where(s => !string.IsNullOrEmpty(s)).ToList();
                _service.Delete(delIds);
                return Json(new ReturnModel
                {
                    Success = true
                    ,
                    Msg = "删除成功！"
                });
            }
            catch (Exception ex)
            {
                return Json(new ReturnModel
                {
                    Success = false,
                    Msg = ex.Message
                });
            }
        }

        public IActionResult Get(string id)
        {
            var role = new RoleDto();
            if (!string.IsNullOrEmpty(id))
                role = _service.QuerySingle(id);
            return Json(new ReturnModel { Data = role });
        }

        /// <summary>
        /// 根据角色获取权限
        /// </summary>
        /// <returns></returns>
        public IActionResult GetMenusByRole(string ids)
        {
            List<TreeModel> treeModels = new List<TreeModel>();
            string[] idArray = ids.Split(',');
            //同时对多个角色授权默认勾选第一个角色的资源
            var roleIds = idArray.Where(s => !string.IsNullOrEmpty(s)).FirstOrDefault();

            var selectMenus = _service.GetAllMenuListByRole(roleIds);

            var menus = _menuAppService.GetAllList();
            foreach (var menu in menus)
            {
                //区别菜单和按钮的图标
                var icon = menu.Type == 0 ? "" : "layui-icon layui-icon-fonts-strong";
                var isChecked = selectMenus.Contains(menu.Id);
                treeModels.Add(new TreeModel()
                {
                    Id = menu.Id,
                    Text = menu.Name,
                    Parent = menu.ParentId == Guid.Empty.ToString() ? "#" : menu.ParentId,
                    IconSkin = icon,
                    Checked = isChecked
                });
            }
            return Json(new ReturnModel() { Data = treeModels });
        }
        /// <summary>
        /// 给角色授权
        /// </summary>
        /// <param name="ids">角色id</param>
        /// <param name="roles">资源权限</param>
        /// <returns></returns>
        public IActionResult SavePermission(string ids,string roles)
        {
            string[] idArray = ids.Split(',');
            //去除空字符串
            var roleIds = idArray.Where(s => !string.IsNullOrEmpty(s)).ToList();
            foreach (var item in roleIds)
            {
                var roleMenus = new List<RoleMenuDto>();
                foreach (var menuId in roles.Split(',').Where(s => !string.IsNullOrEmpty(s)).ToList())
                {
                    roleMenus.Add(new RoleMenuDto { MenuId = menuId, RoleId = item,Id=Guid.NewGuid().ToString() });
                }

                _service.UpdateRoleMenu(item, roleMenus);
            }
            return Json(new ReturnModel { Success = true ,Msg="授权成功"});
        }

    }
}